package org.jupiter.blog.authentic.service;

import io.jsonwebtoken.Claims;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.security.Keys;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.stereotype.Component;

import javax.crypto.SecretKey;
import java.nio.charset.StandardCharsets;
import java.util.Date;
import java.util.List;

@Component
public class TokenService {

	private final SecretKey secretKey = Keys.hmacShaKeyFor(
			"jupiter-secret-jupiter-secret-jupiter-secret".getBytes(StandardCharsets.UTF_8));

	private final long expirationMillis = 24 * 60 * 60 * 1000L; // 1 day

	public String generateToken(UserDetails userDetails) {
		long now = System.currentTimeMillis();
		List<String> authorities = userDetails.getAuthorities().stream()
				.map(GrantedAuthority::getAuthority)
				.toList();

		return Jwts.builder()
				//.claim("authorities", authorities) // 自定义 claims
				.subject(userDetails.getUsername()) // subject
				.issuedAt(new Date(now))            // 签发时间
				.expiration(new Date(now + expirationMillis)) // 过期时间
				.signWith(secretKey, Jwts.SIG.HS256)
				.compact();

	}

	public boolean validateToken(String token) {
		try{
			Jwts.parser()
					.verifyWith(secretKey)
					.build()
					.parseSignedClaims(token);
			return true;
		} catch (Exception e){
			return false;
		}
	}

	public String getUsernameFromToken(String token) {
		Claims claims = Jwts.parser()
				.verifyWith(secretKey)
				.build()
				.parseSignedClaims(token)
				.getPayload();
		return claims.getSubject();
	}
}
